//
//  PageContentView.swift
//  DouYuZB
//
//  Created by 刘耀 on 2017/4/11.
//  Copyright © 2017年 深圳多诺信息科技有限公司. All rights reserved.
//

import UIKit

protocol PageContetntViewDelegate: class {
    func pageContetnView(contetnView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int)
}

private let ContetnCellID = "ContetnCellID"

/// 容器视图
class PageContentView: UIView {
    // MARK: - 定义属性
    fileprivate var isForbidScrollDelegate: Bool = false
    fileprivate var startOffsetX: CGFloat = 0
    fileprivate var childVcs: [UIViewController]
    fileprivate weak var parentViewController: UIViewController?
    
    weak var delegate: PageContetntViewDelegate?
    
    // MARK: - 懒加载
    fileprivate lazy var collectionView: UICollectionView = { [weak self] in
       let layout = UICollectionViewFlowLayout()
        layout.itemSize = (self?.bounds.size)!
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.isPagingEnabled = true
        collectionView.bounces = false
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContetnCellID)
        return collectionView
        
    }()

    // MARK: - 自定义构造函数
    init(frame: CGRect,childVcs: [UIViewController], parentViewController: UIViewController?) {
        self.childVcs = childVcs
        self.parentViewController = parentViewController
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

// MARK: - 设置UI界面
extension PageContentView {
    fileprivate func setupUI() {
        for childVC in childVcs {
            parentViewController?.addChildViewController(childVC)
        }
        //添加UICollectionView
        addSubview(collectionView)
        collectionView.frame = bounds
    }
}

// MARK: - UICollectionViewDataSource
extension PageContentView: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return childVcs.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContetnCellID, for: indexPath)
        
        for view in cell.contentView.subviews {
            view.removeFromSuperview()
        }
        
        let childVc = childVcs[indexPath.item]
        childVc.view.frame = cell.contentView.bounds
        cell.contentView.addSubview(childVc.view)
        return cell
    }
}

// MARK: - UICollectionViewDelegate
extension PageContentView: UICollectionViewDelegate {
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        //判断是否是左还是右
        isForbidScrollDelegate = false
        startOffsetX = scrollView.contentOffset.x
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if isForbidScrollDelegate {
            return
        }
        //1.定义需要获取的数据
        var progress: CGFloat = 0   // 进度
        var sourceIndex: Int = 0    // 源
        var targetIndex: Int = 0    //目标
        
        let currentOffsetX = scrollView.contentOffset.x
        let scrollViewW = scrollView.width
        if currentOffsetX > startOffsetX { // 左滑
            progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)
            sourceIndex = Int(currentOffsetX / scrollViewW)
            targetIndex = sourceIndex + 1
            if targetIndex >= childVcs.count {
                targetIndex = childVcs.count - 1
            }
            // 如果完全滑过去
            if currentOffsetX - startOffsetX == scrollViewW {
                progress = 1
                targetIndex = sourceIndex
            }
        }else {
            // 右滑
            progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW))
            targetIndex = Int(currentOffsetX / scrollViewW)
            sourceIndex = targetIndex + 1
            if  sourceIndex >= childVcs.count  {
                sourceIndex = childVcs.count - 1
            }
        }
        //传递出去
        delegate?.pageContetnView(contetnView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
        
    }
}

// MARK: - 对外暴露的方法
extension PageContentView {
    func setCurrentIndex(current: Int) {
        // 1.记录需要进制执行代理方法
        isForbidScrollDelegate = true
        
        let offsetX = CGFloat(current) * collectionView.width
        
        collectionView.setContentOffset(CGPoint(offsetX, 0), animated: false)
    }
}
